
package others;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;

import java.awt.image.BufferedImage;

import java.util.Random;
import java.io.*;

import javax.imageio.ImageIO;

/**
 *
 * 
 */
public class Image {
	
	//验证图片的宽度
    private int width=80;
    
    //验证图片的高度
    private int height=40;
    
    //验证码字符个数
    private int codeCount=4;
    
    //字体高度
    private int fontSize = 22;
//    private String fontName = "font/wawa.TTF";

    private String code;

    char[] codeSequence={'a','b','c','d','e','f','g','h','i','j','k','l','m',
    		'n','o','p','q','r','s','t','u','v','w','x','y','z',
    		'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
    'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
    'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
   
    public BufferedImage getImage(){
    BufferedImage buffImg=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);//用于存储图片
    	Graphics2D g=buffImg.createGraphics();
    	Random random=new Random();//声明随机数对象
    	


    	g.setColor(Color.BLACK);//设置背景色为黑色
    	g.fillRect(0, 0, width, height);
    	
    	//创建字体
    	g.setColor(Color.WHITE);
    	g.setFont(new Font("simhei", Font.BOLD, fontSize));
    	char []tempCode = new char[4];
    	for(int i = 0; i < codeCount; ++i ){
    		tempCode[i] = codeSequence[random.nextInt(codeSequence.length)];
    		g.drawString(String.valueOf(tempCode[i]), 10 + i * 15, 30);//将随机产生的验证码写到图片中
    	}
    	code = String.valueOf(tempCode);

    	
    	
    	//画边框
    	g.setColor(Color.BLUE);
    	g.drawRect(0, 0, width-1, height-1);
    	g.setColor(Color.YELLOW);
    	
        //画干扰线
    	for(int i=0;i<80;i++){
            g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            int x=random.nextInt(width);
            int y=random.nextInt(height);
            int x1=random.nextInt(12);
            int y1=random.nextInt(12);
            if(x%2 == 0)
                g.drawLine(x, y, x+x1, y+y1);

            else    // 画点
                g.drawOval(x, y, 2, 2);
    	}
       
        g.dispose();
        try{
    		FileOutputStream out = new FileOutputStream("D:/123.jpeg");
    		ImageIO.write(buffImg,"jpeg", out);
    	}catch(IOException e){
    }
        return buffImg ;
    }

	public String getCode() {
		return code;
	}

}
